package cn.com.yto56.cainiao.exponent.elasticsearch.service.engine;

import cn.com.yto56.cainiao.exponent.common.ExponentType;
import cn.com.yto56.cainiao.exponent.common.ExponentTypeMapper;
import cn.com.yto56.cainiao.exponent.dto.ExponentResponse;
import com.alibaba.fastjson.JSONPath;
import org.frameworkset.elasticsearch.entity.MapRestResponse;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public final class Engine4ES {

    private static final String TOTAL_PATH = "$.searchHits.total";
    private static final String BUCKETS_PATH = "$.aggregations.group.buckets";

    public static ExponentResponse read(final ExponentType type, MapRestResponse res) {
        ExponentResponse exponentResponse = new ExponentResponse();
        exponentResponse.setSortId(type.getCode());
        exponentResponse.setType(ExponentTypeMapper.get(type.getName()));
        exponentResponse.setTotal(String.valueOf(JSONPath.eval(res, TOTAL_PATH)));
        exponentResponse.setData(new LinkedHashMap<>());
        List list = (List) JSONPath.eval(res, BUCKETS_PATH);
        if (list != null && list.size() > 0) {
            for (Object o : list) {
                Map<String, String> m = (Map<String, String>) o;
                if (m != null && m.size() > 0) {
                    String key = String.valueOf(m.get("key"));
                    exponentResponse.getData().put(ExponentTypeMapper.get(key), String.valueOf(m.get("doc_count")));
                }
            }
        }

        return exponentResponse;
    }


}
